package zdream.pmfield.stage.message;

import java.util.Objects;

import zdream.pmfield.core.Result;
import zdream.pmfield.data.foe.Foe;
import zdream.pmfield.data.foe.MoveTemplate;
import zdream.pmfield.stage.Stage;
import zdream.pmfield.stage.action.AttackAction;
import zdream.pmfield.stage.action.StageAction;
import zdream.pmfield.stage.object.FoeActor;
import zdream.pmfield.stage.object.Seat;
import zdream.pmfield.stage.object.StageMove;

/**
 * @author Zdream
 * @date 2023-11-13
 * @since 0.0.1
 */
public class ActionRequestReply extends StageReply {
	public final ActionRequestMessage message;
	public final Stage stage;
	public StageAction action;

	public ActionRequestReply(ActionRequestMessage message) {
		this.message = Objects.requireNonNull(message);
		this.stage = message.foe.stage;
	}

	public AttackAction createAttackAction() {
		final AttackAction action = new AttackAction(message.foe);
		this.action = action;
		return action;
	}

	private AttackAction getOrCreateAttackAction() {
		if (this.action == null) {
			return createAttackAction();
		}
		return this.action.asAttack();
	}

	public ActionRequestReply withMove(StageMove move) {
		getOrCreateAttackAction().move = move;
		return this;
	}

	public ActionRequestReply withMove(MoveTemplate move) {
		getOrCreateAttackAction().move = Objects.requireNonNull(message.foe.findMove(move),
				() -> "无法在 " + message.foe + " 中找到技能 " + move);
		return this;
	}

	public ActionRequestReply withTarget(FoeActor targetFoe) {
		getOrCreateAttackAction().targetFoe = targetFoe;
		return this;
	}

	public ActionRequestReply withTarget(Foe foe) {
		getOrCreateAttackAction().targetFoe = Objects.requireNonNull(stage.findFoe(foe),
				() -> "无法在 stage 中找到技能 " + foe);
		return this;
	}

	public ActionRequestReply withSelfTarget() {
		getOrCreateAttackAction().targetFoe = message.foe;
		return this;
	}

	public ActionRequestReply withTarget(Seat targetSeat) {
		getOrCreateAttackAction().targetSeat = targetSeat;
		return this;
	}

	public Result commit() {
		return this.message.commit(this);
	}

	public ActionRequestReply copy() {
		ActionRequestReply reply = new ActionRequestReply(message);
		if (action != null) {
			reply.action = action.copy();
		}
		return reply;
	}
}
